<?php
/**
 * Created by PhpStorm.
 * User: sqq
 * Date: 2018/08/09
 * Time: 下午16:29
 */
class LiveAccessToken extends Eloquent{

    protected $table = "Live_AccessToken";

    //获取直播路径
    public static function getLiveBroadcast($appKey, $secret, $live_sequence_number, $live_equipment_channel){
        $AccessToken = LiveAccessToken::where('appKey',$appKey)->first();
        if($AccessToken){
            if($AccessToken->out_time < Common::currentTimeString()){
                $AccessToken = LiveAccessToken::getAccessToken($appKey, $secret);
                if($AccessToken['code'] != 200){
                    //return $response = array('code' => 1000, 'msg' => '获取AccessToken失败');
                    return $response = array('code' => 30003, 'msg' => '当前设备升级中，暂无法观看');
                }
                $access_token = $AccessToken['data']['accessToken'];
            }else{
                $access_token = $AccessToken->AccessToken;
            }
        }else{
            $AccessToken = LiveAccessToken::getAccessToken($appKey, $secret);
            if($AccessToken['code'] != 200){
                //return $response = array('code' => 1000, 'msg' => '获取AccessToken失败');
                return $response = array('code' => 30003, 'msg' => '当前设备升级中，暂无法观看');
            }
            $access_token = $AccessToken['data']['accessToken'];
        }
        $address_url = Config::get('config.LiveBroadcast_address_url');
        $url = $address_url.'?accessToken='.$access_token.'&source='.$live_sequence_number.':'.$live_equipment_channel;
        $response = LiveAccessToken::getResponse($url);
        $response = json_decode($response,true);
        if(empty($response)) {
            //$response = array('code' => 1001, 'msg' => '获取直播路径失败');
            return $response = array('code' => 30003, 'msg' => '当前设备升级中，暂无法观看');
        }
        return $response;
    }

    //获取AccessToken
    public static function getAccessToken($appkey, $appSecret){
        $AccessToken_url = Config::get('config.LiveBroadcast_AccessToken_url');
        $url = $AccessToken_url.'?appKey='.$appkey.'&appSecret='.$appSecret;
//        $data = array(
//            'appkey' => $appkey,
//            'appSecret' => $appSecret
//        );
        $response = LiveAccessToken::getResponse($url);
        $response = json_decode($response,true);
        if($response['code'] == 200){
            $response = self::saveAccessToken($response,$appkey);
        }else{
            //$response = array('code' => 1000, 'msg' => '获取AccessToken失败');
            return $response = array('code' => 30003, 'msg' => '当前设备升级中，暂无法观看');//
        }

        Log::info("info", array("system" => "api3.0" ,"event" => "getAccessToken", 'input' =>Input::all() ,"output" => $response));
        return $response;
    }

    public static function getResponse($url){
        //模拟post请求
//        $postdata = http_build_query(
//            $data
//        );
        $opts = array('http' =>
            array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => ''
            )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        Log::info("info", array("system" => "api3.0" ,"event" => "getResponse", 'input' =>Input::all() ,"output" => $result));
        return $result;
    }

    public static function saveAccessToken($response,$appkey){
        $AccessToken = LiveAccessToken::where('appKey',$appkey)->first();
        if(is_null($AccessToken)){
            $AccessToken = new LiveAccessToken();
            $AccessToken->created_at = Common::currentTimeString();
        }
        $AccessToken->appKey = $appkey;
        $AccessToken->AccessToken = $response['data']['accessToken'];
        $AccessToken->updated_at = Common::currentTimeString();
        $AccessToken->out_time_stamp = $response['data']['expireTime'];
        $AccessToken->out_time = date("y-m-d H:i:s",($response['data']['expireTime']/1000));
        $AccessToken->save();
        Log::info("info", array("system" => "api3.0" ,"event" => "saveAccessToken", 'input' =>Input::all() ,"output" => $response));
        return $response;
    }

    public static function LiveBroadcast($user_id, $order_id){
        $orders = Orders::where('user_id',$user_id)->where('order_id',$order_id)->first();
        if(empty($orders)){
            //return $response = Lang::get("error.activity_award_order_error_51016");
            return $response = Lang::get("error.LiveComment_not_existence_error_30002");
        }

        //判断是否在营业时间内
        $shops = AhpMaintenanceShops::where('cms_shop_id',$orders->shop_id)->first();
        if(!is_null($shops)){
            //获取当前时间
            $day_time = date('Y-m-d ',time());
            $business_start_time = strtotime($day_time." ".$shops->business_start_time.":00");
            $business_end_time = strtotime($day_time." ".$shops->business_end_time.":00");
            $time = time();
            if(!($business_start_time < $time && $business_end_time > $time)){
                return $response = Lang::get("error.LiveComment_not_existence_error_30002");
            }
        }else{
            return $response = Lang::get("error.LiveComment_not_existence_error_30002");
        }

        //查询订单是否在服务中
        if(in_array($orders['status'],Orders::$order_status_wechat3[4])){
            //查询当前订单是否在工位上
            $station = MaintenanceStationCarStatus::where('order_id',$order_id)->first();
            if(empty($station)){
               //return $response = Lang::get("error.order_not_in_station_error_1023");
               return $response = Lang::get("error.LiveComment_not_existence_error_30002");//
            }
            //查询工位对应的设备序列号以及设备通道
            //后期针对每个工位时候放开
            //$live = MaintenanceStation::where('id',$station->station_id)->where('status',1)->get();
            //每个门店只有一个设备时候使用

            $type = 1;  //1-门店 2-工位 3-无门店无工位（特殊直播）
            if($type == 1){
                $appkey = AhpLiveAppKeySecret::where('status',1)->where('shop_id',$station['shop_id'])->first();
                if(is_null($appkey)){
                    //return $response = Lang::get("error.equipment_not_exist_error_1025");
                    return $response = Lang::get("error.LiveComment_equipment_upgrading_error_30003");
                }
                $live_sequence_number = $appkey['live_sequence_number'];
                $live_equipment_channel = $appkey['live_equipment_channel'];
            }elseif($type == 2){
                $appkey = AhpLiveAppKeySecret::where('status',1)->where('shop_id',$station['shop_id'])->first();
                if(is_null($appkey)){
                    //return $response = Lang::get("error.equipment_not_exist_error_1025");
                    return $response = Lang::get("error.LiveComment_equipment_upgrading_error_30003");
                }
                $station_live = AhpLive::where('status',1)->where('shop_id',$station['shop_id'])->where('station_id',$station['station_id'])->first();
                if(is_null($station_live)){
                    //return $response = Lang::get("error.equipment_not_exist_error_1025");
                    return $response = Lang::get("error.LiveComment_equipment_upgrading_error_30003");
                }
                $live_sequence_number = $station_live['live_sequence_number'];
                $live_equipment_channel = $station_live['live_equipment_channel'];
            }elseif($type == 3){
                $appkey = AhpLiveAppKeySecret::where('status',1)->where('shop_id',0)->first();
                if(is_null($appkey)){
                    return $response = Lang::get("error.equipment_not_exist_error_1025");
                }
                $live_sequence_number = $appkey['live_sequence_number'];
                $live_equipment_channel = $appkey['live_equipment_channel'];
            }else{
                //return $response = Lang::get("error.equipment_not_exist_error_1025");
                return $response = Lang::get("error.LiveComment_not_existence_error_30002");//
            }

//            $live = MaintenanceStation::where('shop_id',$station['shop_id'])->where('status',1)->get();
//            if(is_null($live)){
//                return $response = Lang::get("error.station_not_exist_error_1024");
//            }
//            $live_sequence_number = '';
//            $live_equipment_channel = '';
//            foreach($live as $_key => $_val){
//                if($_val->live_sequence_number != ''){
//                    $live_sequence_number = $_val->live_sequence_number;
//                }
//                if($_val->live_equipment_channel != ''){
//                    $live_equipment_channel = $_val->live_equipment_channel;
//                }
//            }
            $appkeys = $appkey['appKey'];
            $secret = $appkey['Secret'];

            if(!$appkeys || !$secret || !$live_sequence_number || !$live_equipment_channel){
                //return $response = Lang::get("error.equipment_not_exist_error_1025");
                return $response = Lang::get("error.LiveComment_equipment_upgrading_error_30003");
            }

            //获取直播地址
            $response = LiveAccessToken::getLiveBroadcast($appkeys, $secret, $live_sequence_number, $live_equipment_channel);
            if(is_null($response)){
                //return $response = Lang::get("error.Live_address_empty_error_30000");
                return $response = Lang::get("error.LiveComment_equipment_upgrading_error_30003");
            }
        }else{
            //$response = Lang::get("error.order_not_service_error_1022");
            $response = Lang::get("error.LiveComment_not_existence_error_30002");
        }

        //$response = array('code' => 0, 'msg' => 'ok', 'result' => $response);
        return $response;
    }
}